package com.forward.utils;

import com.alibaba.fastjson.JSON;
import com.forward.entity.DollPrintDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @Author: shafei
 * @Date: 2025/02/06 20:19
 * @description： redis消息订阅者
 **/
@Component
public class RedisMessageSubscriber implements MessageListener {

    @Value("${doll.printIp}")
    private String ip;
    @Value("${doll.printPort}")
    private Integer port;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("Received message: " + new String(message.getBody()));
        String messageBody = new String(message.getBody());

        DollPrintDto dollPrintDto = JSON.parseObject(messageBody, DollPrintDto.class);

        System.out.println("dollPrintDto = " + dollPrintDto);

        //这里打印

        Socket clientSocket = null;
        try {
            clientSocket = new Socket(ip, port);

            DataOutputStream outToServer = null;

            outToServer = new DataOutputStream(clientSocket.getOutputStream());

            String one = "介意勿拍拆袋默认微瑕";
            String two = "ID:__________";
            String three = "成交:";
            String four = "05";
            String five = "条形码";
            String six = "12.14";
            String seven = dollPrintDto.getProductId();
            String code1 =
                    "{PC001;0140,0120,2,2,r,00,B=" + one + "|}" +
                            "{PC002;0140,0320,2,2,r,00,B=" + two + "|}" +
                            "{PC003;0140,0440,2,2,r,00,B=" + three + "|}" +
                            "{PC004;0500,0400,8,8,r,00,B=" + four + "|}" +
                            "{PC006;0140,0600,1,1,r,00,B=" + six + "|}" +
                            "{PC007;0340,0600,2,2,r,00,B=" + seven + "|}" +
                            "{XS;I,0001,0000C5000|}";
            String code2 = "{XB00;0140,0400,T,L,06,A,0,M2=" + five + "|}" +
                    "{XS;I,0001,0000C5000|}";

            outToServer.write(code1.getBytes("gb2312"));
            outToServer.write(code2.getBytes("utf-8"));
            clientSocket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
